import axios, { type AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
import { useRouter } from '#app';
import { isString } from 'lodash';
import Cookie from 'js-cookie';

const useHttp = axios.create({
	baseURL: 'http://127.0.0.1:3100/api',
	timeout: 60000,
});

const redirectLogin = () => {
	const router = useRouter();

	if (process.client) {
		router.push('/login');
	} else {
		return navigateTo('/login');
	}
};

useHttp.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
	if (['/auth/login', '/auth/signup']) return config;

	const token = Cookie.get('token');
	if (!token) redirectLogin();

	return config;
});

useHttp.interceptors.response.use(
	(response: AxiosResponse<any, any>): AxiosResponse<any, any> => {
		const { config } = response;
		const { fetchOptions = {} } = config;

		const { success: successString } = fetchOptions;

		if (successString && isString(successString)) {
			message.success(successString);
		}
		if (fetchOptions.response) return response;
		else if (fetchOptions.data) return response.data;
		else return response.data.message;
	},
	(err: AxiosError<any>) => {
		const { response } = err;
		message.error(response?.data?.message ?? '服务器未知错误');
		return Promise.reject(err);
	}
);

export default useHttp;
